<template>
  <div class="search-page">
    <!-- 固定在顶部的搜索区域 -->
    <div class="search-header">
      <van-search
        v-model="searchText"
        placeholder="请输入成员姓名"
        show-action
        @search="handleSearch"
        @cancel="handleCancel"
      />
      <!-- <van-dropdown-menu class="filter-menu">
        <van-dropdown-item
          v-model="filterType"
          :options="typeOptions"
          @change="handleFilterChange"
        />
      </van-dropdown-menu> -->
    </div>

    <!-- 可滚动的列表区域 -->
    <div class="list-container">
      <van-list
        v-model="loading"
        :finished="finished"
        :immediate-check="true"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-for="item in visibleList" :key="item.id" class="row">
          <div class="row-member" @click.stop="handleSelect(item)">
            <div class="selection-container">
              <div
                class="selection-checkbox member-checkbox"
                :class="{ checked: item.checked === true }"
              >
                <span v-if="item.checked === true" class="icon">✓</span>
              </div>
            </div>
            <div class="content">
              <van-icon name="user" />
              <span class="name">{{ item.label }}</span>
            </div>
          </div>
        </div>
      </van-list>
    </div>
  </div>
</template>


<script>
import { mapState } from "vuex";
import Org from "@/components/Org";

export default {
  components: {
    Org,
  },
  name: "About",
  data() {
    return {
      apiTreeData: [],

      searchText: "",
      loading: false,
      finished: false,
      filterType: "person",
      typeOptions: [
        { text: "全部", value: "all" },
        { text: "部门", value: "department" },
        { text: "成员", value: "person" },
      ],
      flatData: [], // 扁平化后的原始数据
      filteredList: [], // 过滤后的完整列表
      visibleList: [], // 当前显示的列表(分页)
      pageSize: 10, // 每页显示数量
      currentPage: 1, // 当前页码
    };
  },
  computed: {
  },
  created() {
    // 生成模拟数据并扁平化
    const treeData = this.generateOrgTree();
    this.flatData = this.flattenTree(treeData);
    this.filterList();
    // console.log(JSON.stringify(this.apiTreeData, null, 2));
  },
  methods: {
    /**
     * 生成混合部门/成员的树形数据
     * @param {number} depth 当前深度（1-5）
     * @param {number} parentId 父节点ID
     * @returns {Array} 生成的树形数据
     */
    generateOrgTree(depth = 1, parentId = 0) {
      // 每层生成5-10个节点
      const nodeCount = Math.floor(Math.random() * 6) + 5;
      const result = [];
      let idCounter = parentId * 100 || 1;

      for (let i = 0; i < 20; i++) {
        const nodeId = idCounter + i;
        // 随机决定当前节点是部门还是成员（深度<5时部门概率更高）
        const isDepartment = depth < 5 ? Math.random() > 0.4 : false;

        const node = {
          id: nodeId,
          label: this.generateLabel(depth, i, isDepartment),
          type: isDepartment ? "department" : "person",
        };

        // 如果是部门且未达最大深度，生成子节点
        if (isDepartment && depth < 3) {
          node.children = this.generateOrgTree(depth + 1, nodeId);
        }

        result.push(node);
      }

      return result;
    },

    /**
     * 生成节点标签（区分部门和成员）
     */
    generateLabel(depth, index, isDepartment) {
      const depTypes = ["研发部", "市场部", "运维部", "测试部", "设计部"];
      const personNames = [
        "张",
        "王",
        "李",
        "赵",
        "刘",
        "陈",
        "杨",
        "黄",
        "周",
        "吴",
      ];
      const secondNames = [
        "明",
        "伟",
        "芳",
        "娜",
        "强",
        "杰",
        "敏",
        "静",
        "磊",
        "洋",
      ];
      const teamNames = ["前端组", "后端组", "算法组", "产品组", "测试组"];
      const positions = ["工程师", "经理", "总监", "助理", "专员"];

      // 使用静态变量记录已用名字
      if (!this.usedNames) {
        this.usedNames = new Set();
      }

      if (depth === 1) {
        return ["集团总部", "产品中心", "技术中心", "运营中心", "财务中心"][
          index % 5
        ];
      }

      if (isDepartment) {
        if (depth === 2) return `${teamNames[index % 5]}`;
        return `${depTypes[index % 5]}${depth}级`;
      } else {
        // 生成不重复的人名
        let fullName;
        let attempt = 0;
        do {
          const firstName = personNames[(index + attempt) % personNames.length];
          const secondName =
            secondNames[(depth + attempt) % secondNames.length];
          fullName = firstName + secondName;
          attempt++;

          // 防止无限循环
          if (attempt > 100) {
            fullName = firstName + secondName + index;
            break;
          }
        } while (this.usedNames.has(fullName));

        this.usedNames.add(fullName);
        return `${fullName}·${positions[index % 5]}`;
      }
    },

    // 给树结构加层级level属性和选中状态checkedStatus属性
    initTree(data, level = 1, parentId = 0) {
      // 处理数组中的每个节点
      return data.map((item) => {
        // 给当前节点添加属性
        item.level = level;
        item.checkedStatus = "unchecked";
        item.parentId = parentId;

        // 如果有子节点，递归处理
        if (item.children && item.children.length) {
          item.children = this.initTree(item.children, level + 1, item.id);
        }

        return item;
      });
    },

    // 扁平化树结构
    flattenTree(treeData) {
      const result = [];
      const flatten = (nodes, level = 1, parentId = null) => {
        nodes.forEach((node) => {
          const flatNode = {
            ...node,
            level,
            parentId,
            checked: false,
          };
          result.push(flatNode);
          if (node.children && node.children.length) {
            flatten(node.children, level + 1, node.id);
          }
        });
      };
      flatten(treeData);
      return result;
    },

    // 搜索处理
    handleSearch() {
      this.currentPage = 1;
      this.filterList();
    },

    // 取消搜索
    handleCancel() {
      this.searchText = "";
      this.currentPage = 1;
      this.filterList();
    },

    // 筛选类型变化
    handleFilterChange() {
      this.currentPage = 1;
      this.filterList();
    },

    // 过滤列表
    filterList() {
      this.filteredList = this.flatData.filter((item) => {
        // 匹配搜索文本
        const matchText =
          !this.searchText || item.label.includes(this.searchText);
        // 匹配类型
        const matchType =
          this.filterType === "all" || item.type === this.filterType;
        return matchText && matchType;
      });

      // 重置分页
      this.visibleList = this.filteredList.slice(0, this.pageSize);
      this.finished = this.filteredList.length <= this.pageSize;
    },

    // 加载更多数据
    onLoad() {
      setTimeout(() => {
        this.currentPage++;
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;

        const newItems = this.filteredList.slice(start, end);
        this.visibleList = [...this.visibleList, ...newItems];

        this.loading = false;
        this.finished = end >= this.filteredList.length;
      }, 500);
    },

    // 选择项目
    handleSelect(item) {
      item.checked = !item.checked;
      this.$forceUpdate();
      this.$emit("select", item);
    },

    // 移除选中成员
    removeSelected(member) {
      const item = this.flatData.find((item) => item.id === member.id);
      if (item) {
        item.checked = false;
        this.$forceUpdate();
      }
    },
  },
};
</script>

<style scoped lang="less">
.search-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.search-header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-menu {
  margin-top: -1px; /* 消除搜索框和菜单之间的间隙 */
}


.list-container {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding: 0 15px;
}

.row {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  background: #fff;
  border-bottom: 1px solid #eae2e2;

  &-department,
  &-member {
    width: 100%;
    display: flex;
    align-items: center;
  }

  .selection-container {
    margin-right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .content {
    flex: 1;
    display: flex;
    align-items: center;
  }

  .name {
    margin-left: 10px;
  }

  .arrow-icon {
    padding: 8px;
  }
}

.selection-checkbox {
  width: 18px;
  height: 18px;
  border: 1px solid #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;

  .icon {
    font-size: 12px;
    color: white;
  }

  &.checked {
    background-color: #1989fa;
    border-color: #1989fa;
  }

  &.indeterminate {
    background-color: #1989fa;
    border-color: #1989fa;
  }

  &.department-checkbox {
    border-radius: 4px;

    &.indeterminate .icon {
      font-weight: bold;
    }
  }
}
</style>